/// 人才发现服务
/// 提供人才列表、搜索、筛选等功能

import 'package:base_flutter/src/network/manager.dart';
import '../models/talent_user_model.dart';
import '../utils/logger.dart';

class TalentService {
  static final TalentService _instance = TalentService._internal();
  factory TalentService() => _instance;
  TalentService._internal();

  final NetworkManager _networkManager = NetworkManager();

  /// 获取发现用户列表
  /// 
  /// [userId] 当前用户ID
  /// [latitude] 纬度（可选，用于计算距离）
  /// [longitude] 经度（可选，用于计算距离）
  /// [limit] 返回数量限制
  Future<List<TalentUserModel>> getDiscoverUsers({
    required int userId,
    double? latitude,
    double? longitude,
    int limit = 20,
  }) async {
    Logger.d('TALENT_SERVICE', '获取发现用户列表, userId: $userId, limit: $limit');

    try {
      final params = <String, dynamic>{
        'userId': userId,
        'limit': limit,
      };
      
      if (latitude != null) params['latitude'] = latitude;
      if (longitude != null) params['longitude'] = longitude;

      final response = await _networkManager.get(
        '/api/discover/users',
        params: params,
      );

      if (response['code'] == 200) {
        final List<dynamic> data = response['data'] ?? [];
        final users = data.map((json) => TalentUserModel.fromJson(json)).toList();
        Logger.d('TALENT_SERVICE', '获取发现用户成功: ${users.length}个');
        return users;
      } else {
        throw Exception(response['message'] ?? '获取用户列表失败');
      }
    } catch (e) {
      Logger.e('TALENT_SERVICE', '获取发现用户失败: $e');
      rethrow;
    }
  }

  /// 搜索用户
  /// 
  /// [keyword] 搜索关键词
  /// [category] 分类筛选
  /// [page] 页码
  /// [size] 每页数量
  Future<List<TalentUserModel>> searchUsers({
    required String keyword,
    String? category,
    int page = 1,
    int size = 20,
  }) async {
    Logger.d('TALENT_SERVICE', '搜索用户, keyword: $keyword, category: $category');

    try {
      final params = <String, dynamic>{
        'keyword': keyword,
        'page': page,
        'size': size,
      };
      
      if (category != null && category != '全部') {
        params['category'] = category;
      }

      final response = await _networkManager.get(
        '/api/user/search',
        params: params,
      );

      if (response['code'] == 200) {
        final data = response['data'];
        List<dynamic> records;
        
        // 兼容分页和非分页返回格式
        if (data is Map && data.containsKey('records')) {
          records = data['records'] ?? [];
        } else if (data is List) {
          records = data;
        } else {
          records = [];
        }
        
        final users = records.map((json) => TalentUserModel.fromJson(json)).toList();
        Logger.d('TALENT_SERVICE', '搜索用户成功: ${users.length}个');
        return users;
      } else {
        throw Exception(response['message'] ?? '搜索用户失败');
      }
    } catch (e) {
      Logger.e('TALENT_SERVICE', '搜索用户失败: $e');
      rethrow;
    }
  }

  /// 获取热门用户
  /// 
  /// [limit] 返回数量
  Future<List<TalentUserModel>> getHotUsers({int limit = 10}) async {
    Logger.d('TALENT_SERVICE', '获取热门用户, limit: $limit');

    try {
      final response = await _networkManager.get(
        '/api/user/hot',
        params: {'limit': limit},
      );

      if (response['code'] == 200) {
        final List<dynamic> data = response['data'] ?? [];
        final users = data.map((json) => TalentUserModel.fromJson(json)).toList();
        Logger.d('TALENT_SERVICE', '获取热门用户成功: ${users.length}个');
        return users;
      } else {
        throw Exception(response['message'] ?? '获取热门用户失败');
      }
    } catch (e) {
      Logger.e('TALENT_SERVICE', '获取热门用户失败: $e');
      rethrow;
    }
  }

  /// 获取推荐用户（基于标签匹配）
  /// 
  /// [userId] 当前用户ID
  /// [limit] 返回数量
  Future<List<TalentUserModel>> getRecommendedUsers({
    required int userId,
    int limit = 10,
  }) async {
    Logger.d('TALENT_SERVICE', '获取推荐用户, userId: $userId');

    try {
      final response = await _networkManager.get(
        '/api/user/recommended',
        params: {
          'userId': userId,
          'limit': limit,
        },
      );

      if (response['code'] == 200) {
        final List<dynamic> data = response['data'] ?? [];
        final users = data.map((json) => TalentUserModel.fromJson(json)).toList();
        Logger.d('TALENT_SERVICE', '获取推荐用户成功: ${users.length}个');
        return users;
      } else {
        throw Exception(response['message'] ?? '获取推荐用户失败');
      }
    } catch (e) {
      Logger.e('TALENT_SERVICE', '获取推荐用户失败: $e');
      rethrow;
    }
  }

  /// 获取用户详情
  /// 
  /// [userId] 用户ID
  Future<TalentUserModel?> getUserDetail(int userId) async {
    Logger.d('TALENT_SERVICE', '获取用户详情, userId: $userId');

    try {
      final response = await _networkManager.get('/api/user/profile/$userId');

      if (response['code'] == 200 && response['data'] != null) {
        final user = TalentUserModel.fromJson(response['data']);
        Logger.d('TALENT_SERVICE', '获取用户详情成功: ${user.nickname}');
        return user;
      }
      return null;
    } catch (e) {
      Logger.e('TALENT_SERVICE', '获取用户详情失败: $e');
      return null;
    }
  }

  /// 获取可用的技能分类
  Future<List<String>> getSkillCategories() async {
    Logger.d('TALENT_SERVICE', '获取技能分类');

    try {
      final response = await _networkManager.get('/api/user/skill-categories');

      if (response['code'] == 200) {
        final List<dynamic> data = response['data'] ?? [];
        final categories = data.map((e) => e.toString()).toList();
        Logger.d('TALENT_SERVICE', '获取技能分类成功: ${categories.length}个');
        return categories;
      }
      // 返回默认分类
      return _getDefaultCategories();
    } catch (e) {
      Logger.w('TALENT_SERVICE', '获取技能分类失败，使用默认分类: $e');
      return _getDefaultCategories();
    }
  }

  /// 获取默认技能分类
  List<String> _getDefaultCategories() {
    return ['全部', '编程', '设计', '营销', '运营', '教育', '医疗', '法律', '金融', '其他'];
  }
}

